/*42865VhVnUExoUYPBd7Qf8rNiCNLij8lDiIsMUoQaQ/Lp395rCKJQyWWOpf97HjW*/
/*
 * @Descripttion: 快速分配，向导分配组织树公共组件
 * @version:
 * @Author: Chendch
 * @Date: 2020-09-30 13:27:04
 * @LastEditors: Chendch
 * @LastEditTime: 2021-09-17 19:01:09
 */
import React, {Component} from 'react';
import {base, ajax} from 'nc-lightapp-front';
import {component} from "../platwapper/index.js";
import PropTypes, { func } from 'prop-types';
const {NCCheckbox} = base;
const { NCTable,NCButton } = component;
import '../uapbdstyle/uapbd_style_common.less';

const propTypes = {
    includeAllText: PropTypes.string,
    rootTreeName: PropTypes.string,
    codeDisplay: PropTypes.string,
    nameDisplay: PropTypes.string,
    assignParams: PropTypes.object,
    assignUrl: PropTypes.string
};

const defaultProps = {
    includeAllText: "",
    rootTreeName: "",
    codeDisplay: "",
    nameDisplay: "",
    assignParams: {},
    assignUrl: ""
};

class OrgSelect extends Component {
    constructor(props) {
        super(props);
        this.treeId = 'assign_org';
        this.state = {};
        this.beforeName = "";
    }

    reset(beforeName = "code") {
        this.beforeName = beforeName;
        let callback = (json,status,inlt) => {
            if(!status) return ;
            let renderState = this.gerState(json);
            this.loadAssignTreeData(renderState, json);
        }
        this.props.MultiInit.getMultiLang({moduleId: 'uapbd-orgselect',domainName: 'uapbd',callback});
    }

    getHasLoadOrgTreeData = ()=>{
        return this.state.hasLoadData;
    }

    loadAssignTreeData = (renderState, json= {}) => {
        const that = this,
            {assignParams, assignUrl} = this.props;
        ajax({
            url: assignUrl || '/nccloud/uapbd/customer/assignTree.do',
            data: Object.assign({}, {
                orgtypeIDs: ['SALEORGTYPE000000000', 'FINANCEORGTYPE000000', 'CREDITCTLREGION00000'],
                isCludeGlobalAndGroupVO: false
            }, assignParams),
            success: (res) => {
                that.state = renderState;
                let treedata = res.data.filter(item => !!item);
                that.state.selectData.datas = new Array();
                that.state.tree.datas = treedata;
                let rootname = json['10140MATERIAL-0000128'];
                let array = [this.state.tree.root].concat(this.treeToList(treedata,new Array()));
                array && array.length>0 && array.forEach(node=>{
                    if(node.pid && node.pid!='root' && node.code){
                        node.refname = this.beforeName == "code" ? `${node.nodeData.code} ${node.name}` : `${node.nodeData[this.beforeName]} ${node.name}`;
                    }
                    if(node.id && node.id=='root' && node.name&&node.name==rootname){
                      node.refname = "root  "+node.name;
                  }
                    if((node.pid == 'root' || node.id =='root')&&node.name&&node.name!=rootname){
                        delete node.code;
                    }
                    //this.state.treeDatas.set(node.refpk,node);
                })
                that.props.syncTree.setSyncTreeData(that.treeId,[Object.assign(that.state.tree.root,{children:treedata})]);
                that.props.syncTree.setNodeChecked(that.treeId,"")
                that.expandFirstNode( [Object.assign(that.state.tree.root,{children:treedata})],that.treeId,that);
                that.state.tree.alldatas = treedata;
                this.state.hasLoadData = true;
                that.setState(that.state);
            }
        });
    }

    gerState = (json) => {
        const {rootTreeName, codeDisplay, nameDisplay} = this.props;
        let state = {
            json: json,
            tree: {
                main: this,
                defNodeCfg: {},
                checkedKeys:[],
                json: {},
                root: {
                    root: true,
                    id:'root',
                    key: 'root',
                    refpk:'root',
                    nodeData:{
                        code:'root',
                        orgclazz:'root'
                      },
                    name : rootTreeName || json["orgselect-000000"],//组织
                    title: rootTreeName || json["orgselect-000000"],
                    refname: rootTreeName || json["orgselect-000000"],
                },
                expandedKeys:['root'],
                datas: [],
                alldatas:[]
            },
            hasLoadData: false,
            table: {
                main: this,
                rowKey: 'id',
                fielid:'lefttable',
                columns: [{
                    title: codeDisplay || json['orgselect-000001'],/* 国际化处理： 组织编码*/
                    dataIndex: 'code',
                    width: '40%'
                }, {
                    title: nameDisplay || json['orgselect-000002'],/* 国际化处理： 组织名称*/
                    dataIndex: 'name',
                    width: '40%'
                }, {
                    title: json['orgselect-000003'],/* 国际化处理： 操作*/
                    dataIndex: 'doit',
                    width: '20%',
                    render: function (text, record, index) {
                        let delFn = function () {
                            const {tree, selectData} = this.state;
                            let datas = selectData.datas;
                            selectData.datas = datas.filter((data) => data.id != record.id);
                            tree.checkedKeys = selectData.datas.map( item => item.id);
                            this.props.syncTree.setNodeChecked(this.treeId, this.state.tree.checkedKeys);
                            this.state.isChild = true;
                            this.setState(this.state);
                        };
                        return (<NCButton onClick={delFn.bind(this)}>{json['orgselect-000004']}</NCButton>);{/* 国际化处理： 删除*/}
                    }.bind(this)
                }]
            },
            selectData: {
                datas: []
            },
            checkedAll:{
                check:false
            },
            isChild:true,
        }
        return state;
    }

    componentWillUnmount() {
        this.props.syncTree.setSyncTreeData(this.treeId,{});
        this.props.syncTree.setNodeChecked(this.treeId,"")
    }
    expandFirstNode = (treeData, id, that) => {
        if(!treeData || !id || !that) return ;

        let pks = [];
        treeData.map( (item, index) => {
            if(item && item.key) {
                pks.push(item.key);
            }
        })
        that.props.syncTree.openNodeByPk(id, pks)
        return ;
    }
    treeToList = (data, list = []) => {
        if (Array.isArray(data)) {
            data.forEach((e) => {
                list.push(e);
                if (e && e.hasOwnProperty('children') && e.children.length>0 ) {
                    this.treeToList(e.children, list);
                }
            });
            return list;
        } else {
            return false;
        }
    }
     /**
     * 展开图标替换
     * @param selectedKeys 选中keys
     * @param e
     */
    openIcon = () => {
        return (
            <i
            className="icon iconfont icon-shu_zk tree-swich"
        />
        )
    }

    closeIcon=()=>{
        return(
        <i
            className="icon iconfont icon-shushouqi tree-swich"
        />
        )}

        /**
     * 树节点展开事件
     */
    onTreeNodeExpand = (expandedKeys)=>{
        this.state.tree.expandedKeys = expandedKeys;
        this.setState(this.state);
    }

    onTreeNodeChecked(props,checkedKeys, e, allcheckedKeys){
        let resultKeys = e.node.props.refpk;//this.getCheckedKeys(checkedKeys,e);
      //设置勾选中的树节点
      let realCheckdList = allcheckedKeys.length ? allcheckedKeys.filter(item => !!item) : [];
      this.state.tree.checkedKeys = checkedKeys.length == 0?[]: resultKeys;
      this.state.tableDatas = [];
      this.setState(this.state,this.resetTableData.bind(this,realCheckdList, e));
    }

    onChangeCheck=(value)=>{
        this.state.isChild=!value;

        let checkedkeys =this.props.syncTree.getCheckedKeys(this.treeId);
        //设置勾选中的树节点
        let allcheckedKeys = [];
        const getcheckedKeys = (node,result = [])=>{
          node.forEach(item=>{
              result.push(
                  item.id
              );
              if(item.hasOwnProperty('children') && item.children.length>0 ){
                  getcheckedKeys(item.children,result);
              }
          })
          return result;
        }
        if(!value){
          this.state.tree.checkedKeys = checkedkeys;
          this.state.tableDatas = [];
          this.setState(this.state,this.resetTableData.bind(this,checkedkeys));
        }else{
          checkedkeys.forEach((item)=>{
            //let node = []
            let node = [this.props.syncTree.getSyncTreeValue(this.treeId,item)];
            allcheckedKeys =allcheckedKeys.concat(getcheckedKeys(node,new Array()));
          })
          this.state.tree.checkedKeys = checkedkeys;
          this.state.tableDatas = [];
          this.setState(this.state,this.resetTableData.bind(this,allcheckedKeys));
        }
      }

    /**
     * 重置表格数据
     */
    resetTableData = (checkedKeys, e)=>{
        debugger
        let result = new Array(),
            searchStr = this.props.syncTree.getSyncTreeSearchVal(this.treeId);
        const getItem = (data,pks,result = [])=>{
            data.forEach(item=>{
                if(pks.includes(item.refpk) && item.refname.toLowerCase().includes(searchStr.toLowerCase())){
                    result.push({
                        id:item.id,
                        name:item.name,
                        code:item.nodeData.code,
                        nodeData:item.nodeData,
                        refpk:item.id,
                        refname:item.name
                    });
                }
                if(item.hasOwnProperty('children') && item.children.length>0 ){
                    getItem(item.children,pks,result);
                }
            })
            return result;
        }
        let tableDatas = getItem(this.state.tree.datas,checkedKeys,new Array());
        tableDatas = tableDatas.filter(d => {return d.nodeData && (d.root || d.nodeData.orgclazz != 'orgtype')})
        this.state.selectData.datas=tableDatas;
        this.setState({tableDatas, selectData: this.state.selectData})
    }

    resetOrgSelect = () => {
        if(!Object.keys(this.state).length) {
            return ;
        }
        this.state.selectData.data = new Array();
        this.state.tree.checkedKeys = new Array();
        this.setState(this.state);
    }

    getData() {
        let returndata = []
        this.state.selectData.datas.map((n)=>{
            if(n.orgclazz !== 'orgtype'){
                returndata.push(n.id)
            }
        });
        return returndata;
    }
    //选择所有
    onCheckAll = (c) => {
        this.getChildList(this.state.tree.datas,c);
        this.setState({
            checkedAll:{
                check:c
            }
        })

    }
    //包含所有下级
    onCheckAllJunior = (c) => {
        this.setState({
            includeAllJunior:{
                check:!c
            }
        });
    }
    // 树的展开的回调函数
    onExpandFn=(keys)=>{
        this.state.tree.expandedKeys = keys;
        this.setState(this.state);
    }
    /**
     * 递归获取所有儿子节点
     * @param array
     * @param checked
     * array 可以是树的node 也可以是树的原始数据
     */
    getChildList = (array,checked)=>{
        let me = this;
        for(let i = 0 ; i<array.length ;i++){
             let t = array[i];
             if(checked){
                 me.state.selectData.datas.push({
                     id: t.id || t.props && t.props.id || 'root',
                     name: t.name || t.props && t.props.name || 'root',
                     code: t.nodeData ? t.nodeData.code : t.props ? t.props.nodeData.code :'root',
                     orgclazz: t.nodeData ? t.nodeData.orgclazz : t.props ? t.props.nodeData.orgclazz :'orgtype'
                 });
             }else{
                 if(t.id){
                     me.state.selectData.datas = me.state.selectData.datas.filter((i) => i.id != t.id)
                 }else if(t.props ){
                     me.state.selectData.datas = me.state.selectData.datas.filter((i) => i.id != t.props.id)
                 }else{
                     t.cheked = checked
                 }
             }
            if(t.children instanceof  Array && t.children.length> 0
                ||t.props && t.props.children instanceof  Array && t.props && t.props.children.length>0 ){
                me.getChildList(t.children || t.props && t.props.children,checked);
            }else{
                continue;
            }
        }
        me.setState(me.state);
}

    selNode = (data, item, info) => {
        if(item){
            this.props.syncTree.setNodeChecked(item.id,item.refpk);
        }

    }
    render() {
        let {syncTree, includeAllText} = this.props,
            {json = {}, table, selectData} = this.state;
        let {createSyncTree} = syncTree;
        let  selectDatas = !!selectData ? selectData.datas.filter((n) => n.orgclazz !== 'orgtype') : [];
        return (
            <div className = 'transfer_tree_container' style={{marginTop: 10}}>
                <div className = 'left-area nc-theme-transfer-wrap-bgc' ref = {dom => this.treeContain = dom} style={{height:'450px',padding:'10px',background:'rgba(249,249,249,1)',width:'calc(50% - 25px)'}}>
                    <div className = 'left-area-nei nc-theme-transfer-list-body-bgc' style={{position:'relative'}}>
                        <div style={{position: "absolute", left: '270px',top: "16px"}}>
                            <span style={{textAlign: 'left', marginBottom: '8px'}}><NCCheckbox
                                checked={!this.state.isChild} onChange={this.onChangeCheck}>{includeAllText || json['orgselect-000005']}</NCCheckbox></span>{/* 国际化处理： 包含所有下级*/}
                        </div>
                        <div  className="syncTreeCom" style={{marginLeft: 20,height:'calc(100% - 40px)'}}>
                            <div className='synctree-area' style={{marginTop:'10px',marginTop:'10px'}}>
                                {createSyncTree({
                                    treeId: this.treeId,
                                    showLine: true,
                                    checkable: true,
                                    needEdit:false ,
                                    onSelectEve:this.selNode,
                                    onCheckEve: this.onTreeNodeChecked.bind(this),   //选择节点回调方法
                                    openIcon:this.openIcon,
                                    closeIcon:this.closeIcon,
                                    defaultExpandAll:false,
                                    checkStrictly:this.state.isChild, //false 勾选下级
                                    onTreeExpand:this.onTreeNodeExpand,
                                    searchType:'filtration',
                                    checkWithCache: true,
                                    noCheckWhenSelect:true
                                })}
                            </div>
                        </div>

                    </div>
                </div>
                {Object.keys(json).length && <div className = 'right-area nc-theme-transfer-wrap-bgc' ref={dom => this.dom = dom} style={{marginLeft:30,height:'450px',padding:'10px',background:'rgba(249,249,249,1)',width:'calc(50% - 25px)',overflow:'hidden'}}>
                    <NCTable {...table} data={selectDatas} {...{
                        bodyStyle: {
                            height: this.dom && this.dom.clientHeight > 10 ? this.dom.clientHeight + "px" : 430,
                            maxHeight: this.dom && this.dom.clientHeight > 10 ? this.dom.clientHeight + "px" : 430,
                            minHeight: 120
                        },
                        useFixedHeader: true,
                    }}></NCTable>
                </div>}
            </div>
        )
    }
}

// 类的默认值
OrgSelect.defaultProps = defaultProps;

// 类的属性类型
OrgSelect.propTypes = propTypes;

export default OrgSelect;

/*42865VhVnUExoUYPBd7Qf8rNiCNLij8lDiIsMUoQaQ/Lp395rCKJQyWWOpf97HjW*/
